package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/app/model"
	"FeedXmh/hub"
	"FeedXmh/redis"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"paco_toolkit/DMXFGW"
	"paco_toolkit/common"
)

var Feednode = feednode{}

type feednode struct {
}

func (a *feednode) GetPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()
	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	key := gconv.String(params["key"])
	//device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])
	hnum := gconv.String(params["hnum"])
	mode := gconv.String(params["mode"])
	day := gconv.String(params["day"])
	online := gconv.String(params["online"])
	alarm := gconv.String(params["alarm"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if mode != "" {
		where += " and mode = " + mode + " "
	}
	if day != "" {
		where += " and day = " + day + " "
	}
	if addr != "" {
		where += fmt.Sprintf(" and addr='%s'", addr)
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if key != "" {
		where += " and CONCAT(addr,sn,hnum) LIKE '%" + key + "%'"
	}
	if online != "" {
		if gconv.Int(online) > 0 {
			where += fmt.Sprintf(" and online=1")
		} else {
			where += fmt.Sprintf(" and ifnull(online,0)=0 ")
		}
	}
	if alarm != "" {
		where += fmt.Sprintf(" and (alarm>0 or alarm_ext>0 ) ")
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		_model := db.Model("v_hzgw_node")
		count, err := _model.Where(where).Count()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			res["count"] = count
			start := limit*page - limit
			if start < 0 {
				start = 0
			}
			if order != "" {
				_model = _model.Order(order)
			} else {
				_model = _model.Order(" tn ASC,hnum asc ")
			}
			records, error := _model.Limit(start, limit).All()
			if error != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				yesterday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
				_where := fmt.Sprintf(" his_date='%s'", yesterday)
				if addr != "" {
					_where += fmt.Sprintf(" and addr='%s'", addr)
				}
				if sn != "" {
					_where += fmt.Sprintf(" and sn='%s'", sn)
				}
				his_data, err := db.GetAll(fmt.Sprintf(" SELECT * FROM t_hzfgw_node_status_his WHERE %s; ", _where))
				if err != nil {
					g.Log().Line(true).Error(err)
				}
				his_list := his_data.List()

				debug_mode := g.Cfg().GetBool("basic.DebugMode")
				for k, item := range list {
					addr := gconv.String(item["addr"])
					sn := gconv.String(item["sn"])
					if !debug_mode {
						device_type := gconv.String(item["device_type"])
						val, err := g.Redis("default").Do("get", fmt.Sprintf("%s:device:%s:%s:node:%s:first_online", model.Redis_Node_Prefix, device_type, addr, sn))
						if err != nil {
							g.Log().Line(true).Error(err)
						} else {
							if val != nil {
								list[k]["first_online"] = gconv.String(val)
							}
						}

						//昨日采食量
						yestoday_feed := redis.GetGwNodePreDayFeed(addr, sn)
						list[k]["yestoday_feed"] = yestoday_feed

						//昨日数据
						for _, v := range his_list {
							_addr := gconv.String(v["addr"])
							_sn := gconv.String(v["sn"])
							if _addr == addr && _sn == sn {
								mode := gconv.Int(item["mode"])
								_model := gconv.String(item["_model"])
								day := gconv.Int(item["day"])
								pig_num := gconv.Int(item["pig_num"])

								var avg_yestoday_feed float32
								if pig_num > 0 {
									avg_yestoday_feed = gconv.Float32(yestoday_feed) / float32(pig_num)
								}
								list[k]["avg_yestoday_feed"] = avg_yestoday_feed
								var health string
								var low, standard, high float32
								low, standard, high = hub.GetStandard(_model, mode, day)
								if low <= avg_yestoday_feed && avg_yestoday_feed <= high {
									//正常采食
									health = "good"
								} else {
									if low > avg_yestoday_feed {
										//低采食
										health = "low"
									} else if high < avg_yestoday_feed {
										//高采食
										health = "high"
									}
								}
								list[k]["yestoday_low_standard"] = low
								list[k]["yestoday_high_standard"] = high
								list[k]["yestoday_standard"] = standard
								list[k]["yestoday_health"] = health
								break
							}
						}
					}

					//采食量达标
					list[k]["health"] = ""
					mode := gconv.Int(item["mode"])
					day := gconv.Int(item["day"])
					_model := gconv.String(item["_model"])
					pig_num := gconv.Int(item["pig_num"])
					if pig_num == 0 {
						if mode == DMXFGW.FEED_MODE_PG || mode == DMXFGW.FEED_MODE_LACTATION {
							pig_num = 1
						} else if mode == DMXFGW.FEED_MODE_NURSE || mode == DMXFGW.FEED_MODE_FAT {
							//使用当前猪只
							pig_num = gconv.Int(redis.GetGwNodePigNum(addr, sn))
						}
					}

					day_use_feed_auto := gconv.Float32(item["day_use_feed_auto"])
					day_use_feed_man := gconv.Float32(item["day_use_feed_man"])
					day_use_feed := day_use_feed_man + day_use_feed_auto
					var avg_day_use_feed float32
					if pig_num > 0 {
						avg_day_use_feed = day_use_feed / float32(pig_num)
					}

					//g.Log().Line(true).Debugf("mode=%d,day=%d,day_use_feed=%.2f", mode, day, day_use_feed)
					list[k]["day_use_feed"] = day_use_feed
					list[k]["avg_day_use_feed"] = avg_day_use_feed

					var health string
					var low, standard, high float32
					low, standard, high = hub.GetStandard(_model, mode, day)
					if low <= avg_day_use_feed && avg_day_use_feed <= high {
						//正常采食
						health = "good"
					} else {
						if low > avg_day_use_feed {
							//低采食
							health = "low"
						} else if high < avg_day_use_feed {
							//高采食
							health = "high"
						}
					}

					list[k]["low_standard"] = low
					list[k]["high_standard"] = high
					list[k]["standard"] = standard
					list[k]["health"] = health

					//昨日下料，昨日下水
					/*yestoday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
							sql := fmt.Sprintf(`SELECT sum(day_use_feed_auto+day_use_feed_man) AS feed
					,SUM(day_use_water_auto+day_use_water_man) as water
					FROM t_hzfgw_node_status_his
					WHERE sn='%s' and his_date='%s';`, sn, yestoday)
							dt1, err := db.GetOne(sql)
							if err != nil {
								g.Log().Line().Error(err)
							} else {
								data1 := dt1.Map()
								list[k]["yestoday_feed"] = data1["feed"]
								list[k]["yestoday_water"] = data1["water"]
							}*/
				}
				res["code"] = 0
				res["data"] = list
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

// Get 栏舍视图显示用，带有饲喂器所有信息
func (a *feednode) Get(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	key := gconv.String(params["key"])
	//device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])
	hnum := gconv.String(params["hnum"])
	mode := gconv.String(params["mode"])
	day := gconv.String(params["day"])

	online := gconv.String(params["online"])
	alarm := gconv.String(params["alarm"])
	//alarm_ext := gconv.String(params["alarm_ext"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if mode != "" {
		where += " and mode = " + mode + " "
	}
	if day != "" {
		where += " and day = " + day + " "
	}

	if addr != "" {
		where += fmt.Sprintf(" and addr='%s'", addr)
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if key != "" {
		where += " and CONCAT(addr,sn,hnum) LIKE '%" + key + "%'"
	}
	if online != "" {
		if gconv.Int(online) > 0 {
			where += fmt.Sprintf(" and online=1")
		} else {
			where += fmt.Sprintf(" and ifnull(online,0)=0 ")
		}
	}
	if alarm != "" {
		where += fmt.Sprintf(" and (alarm>0 or alarm_ext>0 ) ")
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		_model := db.Model("v_hzgw_node").Order(" tn ASC,hnum asc ")
		records, err := _model.Where(where).All()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := records.List()

			yesterday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
			_where := fmt.Sprintf(" his_date='%s'", yesterday)
			if addr != "" {
				_where += fmt.Sprintf(" and addr='%s'", addr)
			}
			if sn != "" {
				_where += fmt.Sprintf(" and sn='%s'", sn)
			}
			his_data, err := db.GetAll(fmt.Sprintf(" SELECT * FROM t_hzfgw_node_status_his WHERE %s; ", _where))
			if err != nil {
				g.Log().Line(true).Error(err)
			}
			his_list := his_data.List()

			debug_mode := g.Cfg().GetBool("basic.DebugMode")
			for k, item := range list {
				addr := gconv.String(item["addr"])
				sn := gconv.String(item["sn"])
				if !debug_mode {
					device_type := gconv.String(item["device_type"])
					val, err := g.Redis("default").Do("get", fmt.Sprintf("%s:device:%s:%s:node:%s:first_online", model.Redis_Node_Prefix, device_type, addr, sn))
					if err != nil {
						g.Log().Line(true).Error(err)
					} else {
						if val != nil {
							list[k]["first_online"] = gconv.String(val)
						}
					}

					//昨日采食量
					yestoday_feed := redis.GetGwNodePreDayFeed(addr, sn)
					list[k]["yestoday_feed"] = yestoday_feed

					//昨日数据
					for _, v := range his_list {
						_addr := gconv.String(v["addr"])
						_sn := gconv.String(v["sn"])
						if _addr == addr && _sn == sn {
							mode := gconv.Int(item["mode"])
							_model := gconv.String(item["_model"])
							day := gconv.Int(item["day"])
							pig_num := gconv.Int(item["pig_num"])

							var avg_yestoday_feed float32
							if pig_num > 0 {
								avg_yestoday_feed = gconv.Float32(yestoday_feed) / float32(pig_num)
							}
							list[k]["avg_yestoday_feed"] = avg_yestoday_feed
							var health string
							var low, standard, high float32
							low, standard, high = hub.GetStandard(_model, mode, day)
							if low <= avg_yestoday_feed && avg_yestoday_feed <= high {
								//正常采食
								health = "good"
							} else {
								if low > avg_yestoday_feed {
									//低采食
									health = "low"
								} else if high < avg_yestoday_feed {
									//高采食
									health = "high"
								}
							}
							list[k]["yestoday_low_standard"] = low
							list[k]["yestoday_high_standard"] = high
							list[k]["yestoday_standard"] = standard
							list[k]["yestoday_health"] = health
							break
						}
					}
				}

				//采食量达标
				list[k]["health"] = ""
				mode := gconv.Int(item["mode"])
				_model := gconv.String(item["_model"])
				day := gconv.Int(item["day"])
				pig_num := gconv.Int(item["pig_num"])
				if pig_num == 0 {
					if mode == DMXFGW.FEED_MODE_PG || mode == DMXFGW.FEED_MODE_LACTATION {
						pig_num = 1
					} else if mode == DMXFGW.FEED_MODE_NURSE || mode == DMXFGW.FEED_MODE_FAT {
						//使用当前猪只
						pig_num = gconv.Int(redis.GetGwNodePigNum(addr, sn))
					}
				}

				day_use_feed_auto := gconv.Float32(item["day_use_feed_auto"])
				day_use_feed_man := gconv.Float32(item["day_use_feed_man"])
				day_use_feed := day_use_feed_man + day_use_feed_auto
				var avg_day_use_feed float32
				if pig_num > 0 {
					avg_day_use_feed = day_use_feed / float32(pig_num)
				}

				//g.Log().Line(true).Debugf("mode=%d,day=%d,day_use_feed=%.2f", mode, day, day_use_feed)
				list[k]["day_use_feed"] = day_use_feed
				list[k]["avg_day_use_feed"] = avg_day_use_feed

				var health string
				var low, standard, high float32
				low, standard, high = hub.GetStandard(_model, mode, day)
				if low <= avg_day_use_feed && avg_day_use_feed <= high {
					//正常采食
					health = "good"
				} else {
					if low > avg_day_use_feed {
						//低采食
						health = "low"
					} else if high < avg_day_use_feed {
						//高采食
						health = "high"
					}
				}

				list[k]["low_standard"] = low
				list[k]["high_standard"] = high
				list[k]["standard"] = standard
				list[k]["health"] = health

				//昨日下料，昨日下水
				/*yestoday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
						sql := fmt.Sprintf(`SELECT sum(day_use_feed_auto+day_use_feed_man) AS feed
				,SUM(day_use_water_auto+day_use_water_man) as water
				FROM t_hzfgw_node_status_his
				WHERE sn='%s' and his_date='%s';`, sn, yestoday)
						dt1, err := db.GetOne(sql)
						if err != nil {
							g.Log().Line().Error(err)
						} else {
							data1 := dt1.Map()
							list[k]["yestoday_feed"] = data1["feed"]
							list[k]["yestoday_water"] = data1["water"]
						}*/
			}
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

// GetList 饲喂列表显示用，饲喂器基本信息(除参数和状态json)
func (a *feednode) GetList(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	key := gconv.String(params["key"])
	//device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])
	hnum := gconv.String(params["hnum"])
	mode := gconv.String(params["mode"])
	day := gconv.String(params["day"])
	online := gconv.String(params["online"])
	alarm := gconv.String(params["alarm"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if hnum != "" {
		where += " and hnum = '" + hnum + "' "
	}
	if mode != "" {
		where += " and mode = " + mode + " "
	}
	if day != "" {
		where += " and day = " + day + " "
	}
	if addr != "" {
		where += fmt.Sprintf(" and addr='%s'", addr)
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if key != "" {
		where += " and CONCAT(addr,sn,hnum) LIKE '%" + key + "%'"
	}
	if online != "" {
		if gconv.Int(online) > 0 {
			where += fmt.Sprintf(" and online=1")
		} else {
			where += fmt.Sprintf(" and ifnull(online,0)=0 ")
		}
	}
	if alarm != "" {
		where += fmt.Sprintf(" and (alarm>0 or alarm_ext>0 ) ")
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		//model := db.Model("v_hzgw_node")
		records, err := db.GetAll(fmt.Sprintf(`SELECT farmid,farmname,houseid,housename,device_type,addr,sn,hnum,tn,mode,enable,son,pig_num,free_feed,feed_plan_id,feed_plan_name,feed_plan_name_new,
online,alarm,alarm_ext,feed_water,day,max_feed,day_use_feed_man,day_use_feed_auto,day_use_water_man,day_use_water_auto,version,date_time,lasttime FROM v_hzgw_node WHERE %s order by tn asc,hnum asc `, where))
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := records.List()
			debug_mode := g.Cfg().GetBool("basic.DebugMode")
			for k, item := range list {
				if !debug_mode {
					addr := gconv.String(item["addr"])
					sn := gconv.String(item["sn"])
					device_type := gconv.String(item["device_type"])
					val, err := g.Redis("default").Do("get", fmt.Sprintf("%s:device:%s:%s:node:%s:first_online", model.Redis_Node_Prefix, device_type, addr, sn))
					if err != nil {
						g.Log().Line(true).Error(err)
					} else {
						if val != nil {
							list[k]["first_online"] = gconv.String(val)
						}
					}

					yestoday_feed := redis.GetGwNodePreDayFeed(addr, sn)
					list[k]["yestoday_feed"] = yestoday_feed
				}

				//昨日下料，昨日下水
				/*yestoday := gtime.Now().AddDate(0, 0, -1).Format(common.DATE_FORMAT)
						sql := fmt.Sprintf(`SELECT sum(day_use_feed_auto+day_use_feed_man) AS feed
				,SUM(day_use_water_auto+day_use_water_man) as water
				FROM t_hzfgw_node_status_his
				WHERE sn='%s' and his_date='%s';`, sn, yestoday)
						dt1, err := db.GetOne(sql)
						if err != nil {
							g.Log().Line().Error(err)
						} else {
							data1 := dt1.Map()
							list[k]["yestoday_feed"] = data1["feed"]
							list[k]["yestoday_water"] = data1["water"]
						}*/
			}
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode) ExportList(r *ghttp.Request) {

}

func (a *feednode) GetSimple(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	key := gconv.String(params["key"])
	//device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if addr != "" {
		where += fmt.Sprintf(" and addr='%s'", addr)
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if key != "" {
		where += " and CONCAT(addr,sn,hnum) LIKE '%" + key + "%'"
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_hzgw_node").Fields("sn,mode,model,alarm,alarm_ext,online,son,pig_num,device_type")
		records, err := model.Where(where).All()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := records.List()
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode) GetCitySort(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	farmid := gconv.String(params["farmid"])
	where := " 1=1 "
	if farmid != "" {
		where += " and farmid=" + farmid
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		//model := db.Model("v_hzgw_node")
		//records, err := model.Where(where).All()

		records, err := db.GetAll(fmt.Sprintf("SELECT city,count(0) AS num FROM v_hzgw_node WHERE %s GROUP BY city ORDER BY num desc;", where))

		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := records.List()
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode) GetProvinceSort(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	farmid := gconv.String(params["farmid"])
	where := " 1=1 "
	if farmid != "" {
		where += " and farmid=" + farmid
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		//model := db.Model("v_hzgw_node")
		//records, err := model.Where(where).All()

		records, err := db.GetAll(fmt.Sprintf("SELECT province,count(0) AS num FROM v_hzgw_node WHERE %s GROUP BY province ORDER BY num desc;", where))

		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := records.List()
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode) SetEarmark(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetFormMap()
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])
	earmark := gconv.String(params["earmark"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	if dao.CheckApiPermission(url, r.Method, userid) {
		list, err := dao.T_hzfgw_node_ext.GetList(fmt.Sprintf(" addr='%s' and sn='%s' ", addr, sn))
		if err != nil {
			g.Log().Line(true).Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			var item gdb.Map
			if len(list) > 0 {
				//存在
				item = list[0]
				item["earmark"] = earmark
				item["update_date"] = gtime.Now().String()
				item["update_user"] = userid
			} else {
				//不存在
				item = gdb.Map{}
				item["addr"] = addr
				item["sn"] = sn
				item["earmark"] = earmark
				item["create_date"] = gtime.Now().String()
				item["create_user"] = userid
			}

			_, e := dao.T_hzfgw_node_ext.Save(item)
			if err != nil {
				res["code"] = -1
				res["msg"] = e.Error()
			} else {
				res["code"] = 0
				res["msg"] = "保存成功"
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *feednode) SetPigType(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetFormMap()
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])
	pig_type := gconv.String(params["pig_type"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	if dao.CheckApiPermission(url, r.Method, userid) {
		list, err := dao.T_hzfgw_node_ext.GetList(fmt.Sprintf(" addr='%s' and sn='%s' ", addr, sn))
		if err != nil {
			g.Log().Line(true).Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			var item gdb.Map
			if len(list) > 0 {
				//存在
				item = list[0]
				item["pig_type"] = pig_type
				item["update_date"] = gtime.Now().String()
				item["update_user"] = userid
			} else {
				//不存在
				item = gdb.Map{}
				item["addr"] = addr
				item["sn"] = sn
				item["pig_type"] = pig_type
				item["create_date"] = gtime.Now().String()
				item["create_user"] = userid
			}

			_, e := dao.T_hzfgw_node_ext.Save(item)
			if err != nil {
				res["code"] = -1
				res["msg"] = e.Error()
			} else {
				res["code"] = 0
				res["msg"] = "保存成功"
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
